# -*- coding: utf-8 -*-
import re
import json
import math
from datetime import datetime
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.common import parse_time
from zc_core.model.items import Catalog, Order, OrderItem, Sku, ItemData
from zc_core.util.batch_gen import time_to_batch_no


# ------------------------------------------

def parse_root_cat(response):
    cats = list()
    rs = json.loads(response.text)
    rows = rs.get('data', [])
    for row in rows:
        if row and len(row):
            for sub_row in row:
                # 一级分类
                cat1 = _build_catalog(sub_row, '')
                cats.append(cat1)

    return cats


def parse_sub_cat(response):
    meta = response.meta
    cat1_id = meta.get('catalog1Id')

    cats = list()
    rs = json.loads(response.text)
    rows = rs.get('data', [])
    for row in rows:
        # 二级分类
        cat2 = _build_catalog(row, cat1_id)
        cats.append(cat2)

        sub_cats = row.get('navChildDto', [])
        for sub_row in sub_cats:
            # 三级分类
            cat3 = _build_catalog(sub_row, cat2.get('catalogId'))
            cats.append(cat3)

    return cats


def _build_catalog(row, parent_id):
    cat = Catalog()
    cat['catalogId'] = row.get('id')
    cat['catalogName'] = row.get('categoryName')
    cat['parentId'] = parent_id
    level = int(row.get('categoryLevel'))
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1

    return cat


# ------------------------------------------

# 解析sku列表页数
def parse_total_page(response, page_size=20):
    json_data = json.loads(response.text)
    return math.ceil(json_data.get('data', {}).get('itemTotal', 0) / page_size)


# 解析sku列表
def parse_sku(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat3_id = meta.get('catalog3Id')

    skus = list()
    rs = json.loads(response.text)
    rows = rs.get('data', {}).get('goodItems', [])
    for row in rows:
        sku = Sku()
        sku['batchNo'] = batch_no
        sku['skuId'] = row.get('id')
        sku['skuName'] = row.get('goodsName')
        sku['supplierName'] = row.get('supplierName', '')
        sku['supplierSkuId'] = row.get('sku', '')
        sku['supplierSkuCode'] = row.get('sku', '')
        sku['originPrice'] = row.get('officialPrice')
        sku['salePrice'] = row.get('goodsPrice')
        sku['skuImg'] = row.get('goodsImagePath', '')
        sku['soldCount'] = row.get('salesVolume', 0)
        sku['supplierSkuLink'] = row.get('goodsUrl', '')
        sku['catalog3Id'] = cat3_id
        cat_helper.fill(sku)
        skus.append(sku)

    return skus


# 解析stock
def parse_stock(response):
    response_json = json.loads(response.text)
    return response_json.get('stock_num')


# 解析详情页
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    cat3_id = meta.get('catalog3Id')
    sold_count = meta.get('soldCount')

    rs = json.loads(response.text)
    goods_item = rs.get('data', {}).get('goodsItem', {})

    if goods_item and 'id' in goods_item:
        item = ItemData()
        # 批次信息
        item['batchNo'] = batch_no
        # 商品ID
        item['skuId'] = sku_id
        # 商品名称
        item['skuName'] = goods_item.get('goodsName')
        # 三级分页
        item['catalog3Id'] = goods_item.get('tertiaryCategory', None) or cat3_id
        #
        item['soldCount'] = sold_count
        # 品牌名称
        item['brandName'] = goods_item.get('brandName', '')
        # 品牌代码
        item['brandCode'] = goods_item.get('brandCode', '')
        # 品牌id
        item['brandId'] = goods_item.get('brandId', '')
        # 单位
        item['unit'] = goods_item.get('saleUnit', '')
        # 主图
        item['skuImg'] = goods_item.get('goodsImagePath', '')
        # 现价
        item['salePrice'] = goods_item.get('goodsPrice')
        # 原价
        item['originPrice'] = goods_item.get('officialPrice', None) or item['salePrice']
        # 商品链接
        item['supplierSkuLink'] = goods_item.get('goodsUrl')
        # 供应商Id
        item['supplierId'] = goods_item.get('supplierId')
        # 供应商Code
        item['supplierCode'] = goods_item.get('supplierCode')
        # 供应商名称
        item['supplierName'] = goods_item.get('supplierName')
        # 商品型号
        item['brandModel'] = goods_item.get('typeNo')
        # 供应商skuId
        item['supplierSkuId'] = goods_item.get('sku')
        # 供应商skuCode
        item['supplierSkuCode'] = goods_item.get('sku')
        # 商品库存
        item['stock'] = goods_item.get('goodsStock')
        # 交付日期
        delivery_day = goods_item.get('deliveryDate')
        if delivery_day != '/无':
            item['deliveryDay'] = delivery_day
        return item


# 解析order列表
def parse_order_list(response):
    json_data = json.loads(response.text)
    pages = list()
    for i in json_data['data']['records']:
        order = Order()
        order_time = parse_time(i['gmtCreate'].replace('T', ' ').split('.')[0], fmt='%Y-%m-%d %H:%M:%S')
        id = i['id']
        order['id'] = id
        order['url'] = "https://agshop.delinzl.cn/api/unitenotice/info?id=" + id
        order['orderTime'] = order_time
        order['batchNo'] = time_to_batch_no(order_time)
        order['genTime'] = datetime.utcnow()
        pages.append(order)

    return pages


# 解析order列表页数
def parse_order_page(response):
    json_data = json.loads(response.text)
    return int(json_data['data']['pages'])


# 解析订单详情
def parse_order_item(response):
    json_data = json.loads(response.text)
    order_time = parse_time(json_data['data']['publishTime'].replace('T', ' '), fmt='%Y-%m-%d %H:%M:%S')
    order = OrderItem()
    content = re.findall('商品名称:(.*?)备注', json_data['data']['content'])
    order_list = list()
    for index, i in enumerate(content):
        order['id'] = '{}_{}'.format(json_data['data']['id'], index)
        order['orderId'] = json_data['data']['id']
        order['skuId'] = re.search('''/detail\?id=(.*?)\'''', i).group(1)
        if re.search('数量:(.*?)<br>', i):
            order['count'] = re.search('数量:(.*?)<br>', i).group(1)
        order['orderCode'] = \
            [i.get('content') for i in json_data['data']['noticeDetailDtoList'] if i.get('title') == "订单编号"][0]
        order['orderDept'] = "默认"
        order['deptId'] = "agshop_default_dept_id"
        order['orderTime'] = order_time
        order['batchNo'] = time_to_batch_no(order_time)
        order['genTime'] = datetime.utcnow()
        order_list.append(order)
    return order_list
